package cn.com.hbhgkj.dao.hibernate;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import cn.com.hbhgkj.bussiness.ReviewCode;
import cn.com.hbhgkj.common.DaoException;
import cn.com.hbhgkj.common.Pagination;
import cn.com.hbhgkj.dao.CopyrightAlterationDao;
import cn.com.hbhgkj.pojo.CopyrightAlteration;
import cn.com.hbhgkj.pojo.User;

public class CopyrightAlterationDaoImpl extends
		GenericDaoImpl<CopyrightAlteration, Long> implements
		CopyrightAlterationDao {

	public List<CopyrightAlteration> findByApplicant(User applicant,Pagination pagination)
			throws DaoException {
		try {
			DetachedCriteria criteria = this.createCriteria();
			criteria.add(Restrictions.eq("applicant", applicant));
			pagination.setTotalCount(this.getTotalCount(criteria));
			return this.getHibernateTemplate().findByCriteria(criteria,pagination.getStart(), pagination.getPageSize());
		} catch (Exception e) {
			throw new DaoException(e);
		}
	}

	public List<CopyrightAlteration> findByReviewCodes(
			ReviewCode[] reviewCodes, Pagination pagination)
			throws DaoException {
		try {
			DetachedCriteria criteria = this.createCriteria();
			Object[] codes = new Object[reviewCodes.length];
			for (int i = 0; i < reviewCodes.length; i++) {
				codes[i] = reviewCodes[i].getValue();
			}
			criteria.add(Restrictions.in("state", codes));

			pagination.setTotalCount(this.getTotalCount(criteria));
			return this.getHibernateTemplate().findByCriteria(criteria,
					pagination.getStart(), pagination.getPageSize());
		} catch (Exception e) {
			throw new DaoException(e);
		}
	}

	public List<CopyrightAlteration> findByReviewCode(ReviewCode reviewCode,
			Pagination pagination) throws DaoException {
		try {
			DetachedCriteria criteria = this.createCriteria();
			criteria.add(Restrictions.eq("state", reviewCode.getValue()));
			pagination.setTotalCount(this.getTotalCount(criteria));
			return this.getHibernateTemplate().findByCriteria(criteria,
					pagination.getStart(), pagination.getPageSize());
		} catch (Exception e) {
			throw new DaoException(e);
		}
	}

	public void updateState(User user, CopyrightAlteration ca)
			throws DaoException {
		try {
			CopyrightAlteration entity = this.get(ca.getId());
			entity.setState(ca.getState());
			entity.setReviewer(user);
		} catch (Exception e) {
			throw new DaoException(e);
		}
	}
}
